﻿ using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Triad.Controls
{
    /// <summary>
    /// A Single Clickable button for ASP.Net. (Disables the button immediatly and *before* posting back to the server.)
    /// </summary>
    /// <remarks>
    /// Author: tim.fischer,   8/25/2008 - 2:12 PM
    /// Modified By: 
    /// </remarks>
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:tfSingleClickBtn runat=server></{0}:tfSingleClickBtn>")]
    public class tfSingleClickButton : Button
    {
        /// <summary>
        /// Gets or sets the delay in ms.
        /// </summary>
        /// <value>The delay in ms.</value>
        /// <remarks>
        /// Author: tim.fischer,   8/25/2008 - 2:11 PM
        /// Modified By: 
        /// </remarks>
       public int DelayInMs
        {
            get
            {
                if (ViewState["DelayInMs"] == null) return 20;
                return (int)ViewState["DelayInMs"];
            }
            set
            {
                ViewState["DelayInMs"] = value;
            }
        }

       /// <summary>
       /// Renders the control to the specified HTML writer.
       /// </summary>
       /// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter"/> object that receives the control content.</param>
       /// <remarks>
       /// Author: tim.fischer,   8/25/2008 - 2:11 PM
       /// Modified By: 
       /// </remarks>
        protected override void Render(HtmlTextWriter writer)
        {
            string disableMySelf = "document.getElementById('" + ClientID + "').disabled = true;";
            string postIt = Page.ClientScript.GetPostBackEventReference(this, string.Empty);

            string functionName = "DelayedClick" + ClientID;
            var sb = new StringBuilder();
            sb.Append("<script type=text/javascript >function "); 
            sb.Append(functionName); 
            sb.Append("(){");
            sb.Append(postIt); 
            sb.Append(";}</script>"); 
            Attributes.Add("onclick", disableMySelf + ";" + "setTimeout('" + functionName + "()',"+ DelayInMs + ");return false");            
            writer.Write(sb.ToString()); // Write the javascript FIRST so it is available on click!
            base.Render(writer);            
        }              

    } //End Class
} //End Namespace

